﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;

namespace Eniux.Web.Core
{
    public class UIElementSizeThumb:Grid
    {
        private Thumb Controller;
        public UIElementSizeThumb()
        {
            Controller = new Thumb();
            this.Children.Add(Controller);
            Controller.DragDelta += new DragDeltaEventHandler(Controller_DragDelta);
        }

        void Controller_DragDelta(object sender, DragDeltaEventArgs e)
        {
            ContentControl element = Controller.DataContext as ContentControl;
            MatrixTransform matrix;
            Matrix mat;
            if (element != null)
            {
                matrix = element.RenderTransform as MatrixTransform;
                mat = matrix.Matrix;
                double deltaVertical, deltaHorizontal;

                switch (this.VerticalAlignment)
                {
                    case VerticalAlignment.Bottom:
                        deltaVertical = Math.Min(-e.VerticalChange, element.ActualHeight - element.MinHeight);
                        if (element.Height - deltaVertical >= 0)
                            element.Height -= deltaVertical;
                        break;
                    case VerticalAlignment.Top:
                        if (element.Height - e.VerticalChange >= element.MinHeight)
                        {
                            element.Height -= e.VerticalChange;
                            mat.OffsetY += e.VerticalChange;
                            matrix.Matrix = mat;
                        }
                        break;
                    default:
                        break;
                }

                switch (this.HorizontalAlignment)
                {
                    case HorizontalAlignment.Left:
                        if (element.Width - e.HorizontalChange >= element.MinWidth)
                        {
                            element.Width -= e.HorizontalChange;
                            mat.OffsetX += e.HorizontalChange;
                            matrix.Matrix = mat;
                            element.RenderTransform = matrix;
                        }
                        break;
                    case HorizontalAlignment.Right:
                        deltaHorizontal = Math.Min(-e.HorizontalChange, element.ActualWidth - element.MinWidth);
                        if (element.Width - deltaHorizontal >= 0)
                            element.Width -= deltaHorizontal;
                        break;
                    default:
                        break;
                }
            }
        }
        
    }
}
